package com.glory.good_dark.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.glory.good_dark.R;
import com.glory.good_dark.application.App;
import com.glory.good_dark.entity.UserEntity;
import com.glory.good_dark.entity.response.BaseEntity;
import com.glory.good_dark.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.base.FreeUI_BaseActivity;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_DownloadFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_VersionEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_NetUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_SharePreferencesUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_PasswordEditText;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * @author yi.zhang
 * @date 2019/6/10
 * @desc 登录界面
 */
public class LoginActivity extends FreeUI_BaseActivity implements EasyPermissions.PermissionCallbacks {

    @BindView(R.id.ivSetting)
    ImageView ivSetting;
    @BindView(R.id.logoIcon)
    ImageView logoIcon;
    @BindView(R.id.etMobile)
    FreeUI_ClearEditText etMobile;
    @BindView(R.id.etPassword)
    FreeUI_PasswordEditText etPassword;
    @BindView(R.id.btnLogin)
    Button btnLogin;

    private static final int PERMISSIONS_REQUEST_CODE = 10;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {
        App.WEB_URL = FreeApi_SharePreferencesUtils.getSharePre("GOODARK_FILE", "WEB_URL", App.WEB_URL, App.app);
        App.EQPID = FreeApi_SharePreferencesUtils.getSharePre("GOODARK_FILE", "EQP_ID", App.EQPID, App.app);
        App.UPDATA_URL = FreeApi_SharePreferencesUtils.getSharePre("GOODARK_FILE", "UPDATA_URL", App.UPDATA_URL, App.app);
        etMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                for(int i = s.length(); i > 0; i--){

                    if(s.subSequence(i-1, i).toString().equals("\n"))
                        s.replace(i-1, i, "");
                }
            }
        });
        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                for(int i = s.length(); i > 0; i--){

                    if(s.subSequence(i-1, i).toString().equals("\n"))
                        s.replace(i-1, i, "");
                }
            }
        });
        detectionUpdate();
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @OnClick({R.id.ivSetting, R.id.btnLogin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivSetting:
                FreeApi_Utils.skipWithExtraIntent("header", LoginActivity.this, SettingActivity.class);
                break;
            case R.id.btnLogin:
                if (etMobile.getText().toString().trim().length() == 0) {
                    showToast("请输入用户名", false);
                    return;
                }
                if (etPassword.getText().toString().trim().length() == 0) {
                    showToast("请输入密码", false);
                    return;
                }
                requestPermission();
                break;
        }
    }

    private void Login()
    {
        FreeUI_EntityCallBack<BaseEntity<UserEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<UserEntity>>
                (new TypeToken<BaseEntity<UserEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<UserEntity>> response) {
                if (response.body().isSuccess(getApplicationContext(),getSupportFragmentManager())) {
                    UserEntity loginEntity = response.body().getData().getBody();
                    App.userEntity = loginEntity;
                    startMain();
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<UserEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PDALoginRequest");
            }
        };

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("WORK_NO", etMobile.getText().toString().trim());
        jsonObject.addProperty("PASSWORD", etPassword.getText().toString().trim());
        jsonObject.addProperty("ISCHANGEPASSWORD","0");
        NetUtils.requestPostNet(App.WEB_URL + "/api/PDA", this, callBack,"PDALogIn",jsonObject);

//        FreeApi_SharePreferencesUtils.setSharePre("GOODARK_FILE", "USERNAME", etMobile.getText().toString().trim(), App.app);
//        FreeApi_SharePreferencesUtils.setSharePre("GOODARK_FILE", "PASSWORD", etPassword.getText().toString().trim(), App.app);
//        FreeApi_ActivityManager.getActivityManager().finishAllActivity();
//        UserEntity userEntity = new UserEntity();
//        userEntity.setNAME("admin");
//        App.userEntity = userEntity;
//        FreeApi_Utils.skipWithExtraIntent("header", LoginActivity.this, MainActivity.class);
    }

    private void startMain() {
        FreeApi_ActivityManager.getActivityManager().finishAllActivity();
        FreeApi_Utils.skipWithExtraIntent("", LoginActivity.this, MainActivity.class);
        FreeApi_SharePreferencesUtils.setSharePre("GOODARK_FILE", "USERNAME", etMobile.getText().toString().trim(), App.app);
        FreeApi_SharePreferencesUtils.setSharePre("GOODARK_FILE", "PASSWORD", etPassword.getText().toString().trim(), App.app);
    }



    @AfterPermissionGranted(PERMISSIONS_REQUEST_CODE)
    private void requestPermission(){
        String[] perms = {Manifest.permission.READ_PHONE_STATE,Manifest.permission.WRITE_EXTERNAL_STORAGE};
        //权限判断，第一次弹出系统的授权提示框
        if (EasyPermissions.hasPermissions(this, perms)) {
            //@AfterPermissionGranted 有权限直接执行 todo...
            Login();
        }else {
            //没有权限的话，先提示，点确定后弹出系统的授权提示框
            EasyPermissions.requestPermissions(this, "程序运行需要权限",
                    PERMISSIONS_REQUEST_CODE, perms);
        }
    }

    /**
     * 允许权限成功后触发
     */
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    /**
     * 禁止权限后触发
     */
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        showToast("用户授权失败",false);
        /**
         * 若是在权限弹窗中，用户勾选了'NEVER ASK AGAIN.'或者'不在提示'，且拒绝权限。
         * 这时候，需要跳转到设置界面去，让用户手动开启。
         */
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //当从软件设置界面，返回当前程序时候
            case AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE:
                //执行Toast显示或者其他逻辑处理操作
                break;
        }
    }

    private void detectionUpdate()
    {
        PackageManager manager = getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = info.versionName;
        FreeUI_EntityCallBack<FreeUI_VersionEntity> callBack = new FreeUI_EntityCallBack<FreeUI_VersionEntity>
                (new TypeToken<FreeUI_VersionEntity>() {
                }.getType()) {

            @Override
            public void onSuccess(Response<FreeUI_VersionEntity> response) {
                FreeUI_VersionEntity entity = response.body();
                entity.setCurrentVersion(version);
                int code  = compareVersion(version,entity.getVersion());
                if(code == -1)
                {
                    FreeUI_DownloadFragmentDialog downloadFragmentDialog = new FreeUI_DownloadFragmentDialog();
                    downloadFragmentDialog.setData(entity);
                    downloadFragmentDialog.show(getSupportFragmentManager(),"DOWNLOAD");
                }
            }

            @Override
            public void onError
                    (Response<FreeUI_VersionEntity> response) {
                super.onError(response);
            }
        };
        Map<String, String> map = new HashMap<>();
        FreeApi_NetUtils.requestGetNet(App.UPDATA_URL+"/Version.txt", this, map, callBack);
    }

    /**
     * 版本号比较
     *
     * @param version1
     * @param version2
     * @return
     */
    public int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        Log.d("HomePageActivity", "version1Array=="+version1Array.length);
        Log.d("HomePageActivity", "version2Array=="+version2Array.length);
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        Log.d("HomePageActivity", "verTag2=2222="+version1Array[index]);
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }
}
